import groovy.grape.Grape

Grape.grab(group: 'javax.mail', module: 'mail', version: '1.4.3', classLoader: this.class.classLoader.rootLoader)
Grape.grab(group: 'org.apache.ant', module: 'ant-javamail', version: '1.7.1', classLoader: this.class.classLoader.rootLoader)

def startTime = new File('/home/ubuntu/runningAt.txt')
startTime.text = "Running at ${new Date()}"
def urlConn = new URL('http://casework.cloudfoundry.com').openConnection()
urlConn.setConnectTimeout(600)
urlConn.setReadTimeout(600)

try {
    if (urlConn.responseCode != 200) {
        restartApp("None 200 - $urlConn.responseCode")
    } else {
        def file = new File('/home/ubuntu/lastCheck.txt')
        file.text = "Run at ${new Date()}"
        println "Run at ${new Date()}"
    }
} catch ( e) {
    restartApp("Error - ${e.message}")
}


void restartApp(String message) {
    def target = "vmc target api.cloudfoundry.com".execute()
    target.waitFor()
    target.exitValue()
    target.in.text

    def login = "vmc login --email glenn.saqui+cloudFoundry@gmail.com --passwd xKZnNRwd".execute()
    login.waitFor()
    login.exitValue()
    login.in.text

    def restart = "vmc restart casework".execute()
    restart.waitFor()
    restart.exitValue()
    restart.in.text
    def file = new File('/home/ubuntu/lastRestart.txt')
    file << "Failed on - ${new Date() } \n"
    sendMail(message)
}

void sendMail(String msg) {
    def content = """
     Dude,

     The freaking server crashed at ${new Date()}

     Reason: $msg
     """

    new AntBuilder().mail(
            mailhost: "smtp.gmail.com",
            mailport: 465,
            ssl: "on",
            user: "glenn.saqui@gmail.com",
            password: "sexysonja1980",
            subject: "Website - reporting a crash") {
        from(address: "glenn.saqui@gmail.com")
        to(address: "glenn.saqui@gmail.com")
        message(mimetype: "text/html", content)
    }
}
